﻿using System;
using System.Globalization;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Shell32;
using Furty.Windows.Forms;
using Microsoft.Win32;
using System.Linq;

 
namespace Exploreader
{
    public partial class FormMain : Form
    {
        string gSelectedPathAndFileName;
        bool gNewTextLoaded = false;
        bool gTextContentChanged = false;

        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            try
            {
                dataGridView1.Enabled = false;
                folderTreeView1.InitFolderTreeView();//Folder initiate      //fileListBox1.Path = GetSelectedPath(); fileListBox1.Refresh();
                PopulateExts(GetSelectedPath());
                this.menuStrip1.Show();

                //Initalizing the datagrid.
                //dataGridView1.Columns.Add("FileName", "Name");
                //dataGridView1.Columns.Add("Size", "Size(KB)");
                //dataGridView1.Columns.Add("Ext", "Ext");
                //dataGridView1.Columns.Add("CreateTime", "CreateTime");
                //dataGridView1.Columns.Add("ModifiedTime", "ModifiedTime");
                //dataGridView1.Columns.Add("FullPath", "FullPath");
            
                PopulateDataGrid(".*");
            }
            catch (Exception ex)
            {
                ErrMsg(ex, "FormLoad");
            }
        }
        
        //Populate Data Grid View:
        private void PopulateDataGrid(string ext)
        {
            this.dataGridView1.Enabled = false;
            DirectoryInfo DirInfo = new DirectoryInfo(GetSelectedPath());//file list initially load to desktop
            FileInfo[] FI;
            FI = DirInfo.GetFiles("*" + ext.ToString());

            dataGridView1.DataSource = FI;
            int[] validColumns = new int[] { 0, 1, 7, 8, 12 };
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
                if (!validColumns.Contains(i))
                    dataGridView1.Columns[i].Visible = false;

            //foreach (FileInfo oFileInfo in FI) dataGridView1.Rows.Add( oFileInfo.Name,Convert.ToDouble(oFileInfo.Length)/1024,oFileInfo.Extension,oFileInfo.CreationTime,oFileInfo.LastWriteTime,oFileInfo.FullName);    
            dataGridView1.Refresh();
            dataGridView1.Enabled = true;
            
        }

        //Defaulting to Desktop when nothing is selected.
        private string GetSelectedPath()
        {
            string lPath = this.folderTreeView1.GetSelectedNodePath();
            if (lPath.Length < 1)
                lPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);//file list initially load to desktop
            return lPath;
        }
              
        //When ever a folder is selected, reload the FileList
        private void folderTreeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
           //PopulateExts(this.folderTreeView1.GetSelectedNodePath().ToString());
           PopulateExts(GetSelectedPath());
           PopulateDataGrid(".*");
        }
        
        //populate Exts when a folder is selected.
        private void PopulateExts(string lPath)
        {
            try
            {
                this.dataGridView1.Enabled = false;
                this.comboBoxExtList.Items.Clear(); //this.checkedListBoxExtList.ColumnWidth = 100;

                string[] AvailableExts;
                //string[] filesArray = Directory.GetFiles(@lPath,"*.*");

                DirectoryInfo DirInfo = new DirectoryInfo(GetSelectedPath());//file list initially load to desktop
                FileInfo[] FI;
                FI = DirInfo.GetFiles("*.*");
                
                
                AvailableExts = new string[FI.Count()];

                for (int i = 0; i < FI.Count(); i++) // Populating all available extensions array:
                    AvailableExts[i] = FI[i].Extension;
                
                string[] DistinctExts = AvailableExts.Distinct().ToArray(); // Distinct Extensions array.

                for (int i = 0; i < DistinctExts.Count(); i++)
                    this.comboBoxExtList.Items.Add(DistinctExts[i].ToString());

                this.comboBoxExtList.Sorted = true;
                this.comboBoxExtList.Items.Add(".*");
                this.comboBoxExtList.SelectedIndex = 0;

                lblLink.Text = lPath;
                lblAppStatus.Text = "Exts count:" + comboBoxExtList.Items.Count.ToString(); //Status update
                comboBoxExtList.DropDownHeight = comboBoxExtList.Items.Count * 25;
            }
            catch (Exception ex)
            {
                ErrMsg(ex, "Populate Extension List");
            }
        }
        
        //Try's to read the text stream and returns the text.
        private void ReadTextFile(string lFilepath)
        { 
            if (!System.IO.File.Exists(lFilepath))
                throw new Exception("There is a problem opening file '" + lFilepath + "'.");

            try
            {
                
                System.IO.StreamReader reader = new System.IO.StreamReader(lFilepath);
                StringBuilder sb = new StringBuilder();
                sb.Append(reader.ReadToEnd());
                this.textBoxContent.Text = sb.ToString();
                this.tabPage2.Text = lFilepath;
                reader.Close();
            }
            catch (Exception ex)
            {
                ErrMsg(ex,"ReadTextFile");
                lblAppStatus.Text = "Error Opening the file" + lFilepath;
            }
        }
        
        //Handling All Error Messages in this section of Code:
        private void ErrMsg(Exception ex,string lErrSource)
        {
            lblAppStatus.Text = "Error Occured!";

            string msg;

            msg = "Error message:" + ex.Message
                + "\nHelpLink: " + ex.HelpLink
                + "\nSource:" + ex.Source.ToString()
                + "\nData:" + ex.Data.ToString();

            if (ex.Message.Contains("OutOfMemory"))
                msg = "Helpful Tip: Out of memory exception is caused by trying to open a large file of Size:"
                       // + gSelectedFileSize
                        + ".\n    - If this machine has enough memory to handle such files, Close all other programs and try again or \n    - Increase the memory of the machine to handle files of such size.\n\n\n"
                        + msg.ToString();

            MessageBox.Show(msg, "Source: " + lErrSource +"/"+ ex.Source + "    -Browsepad", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
         }

        private void OpenFile(string lFullName) 
        {
            try
            {

                lblAppStatus.Text = "Opening File"; //status update

                ReadTextFile(lFullName); //Reading Text file
                OpenWebPage(lFullName);  //showing in on the web page.
                lblAppStatus.Text = "File Opened.";
                
            }
            catch (Exception ex)
            {
                ErrMsg(ex, "OpenFile");
                lblAppStatus.Text = "Error Opening the File " + lFullName;
            }
        }

        //Getting filename from data Grid and loading that file in text box and Web content
        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView1.Enabled == true)
                {
                    lblAppStatus.Text=dataGridView1.SelectedCells[6].Value.ToString();
                    OpenFile(dataGridView1.SelectedCells[6].Value.ToString());
                }

            }
            catch (Exception ex)
            {
                ErrMsg(ex, "caused by dataGrid File list SelectionChanged event.");
                lblAppStatus.Text = "Error Opening the File " + dataGridView1.SelectedCells[6].Value.ToString();
            }
        }

        //on extension selected event, re-populate filelist.
        private void comboBoxExtList_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.dataGridView1.Enabled = false;
            PopulateDataGrid(this.comboBoxExtList.SelectedItem.ToString());
        }

        private void OpenWebPage(string strURI)
        {
            try
            {
                this.webBrowserContent.Url = new Uri(strURI);
                this.tabPage1.Text = strURI;
            }
            catch (Exception ex)
            {
                ErrMsg(ex, "Occured While opening in Web Page tab");
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (dataGridView1.Enabled == true)
                {
                    lblAppStatus.Text = "Opening " +dataGridView1.SelectedCells[6].Value.ToString();
                    OpenFile(dataGridView1.SelectedCells[6].Value.ToString());
//                    this.Text = dataGridView1.SelectedCells[0].Value.ToString();
                }
            }
            catch (Exception ex)
            {
                ErrMsg(ex, "caused by dataGrid File list CellContentClick event.");
            }
        }

        private void ToolStripMenuItemWordWrap_Click(object sender, EventArgs e)
        {
            WordWrap();
        }
        private void WordWrap()
        {
            if (ToolStripMenuItemWordWrap.Image == Browsepad.Properties.Resources.CheckedCheckbox)
            {
                textBoxContent.WordWrap = false;
                ToolStripMenuItemWordWrap.Image = Browsepad.Properties.Resources.EmptyCheckbox;
            }
            else
            {
                textBoxContent.WordWrap = true;
                ToolStripMenuItemWordWrap.Image = Browsepad.Properties.Resources.CheckedCheckbox;
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CloseThisApp();
        }
        private void CloseThisApp()
        {
            if (gTextContentChanged == false)
                this.Close();
            else 
            {
                DialogResult dr = MessageBox.Show("Do you want to save the file Before closing.", "Browsepad",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Hand);
                if (dr == DialogResult.Yes)
                    SaveFile("Give file Name");
                else if(dr == DialogResult.No)
                    this.Close();
                else 
                    this.Show();
            }

            //Add save procedure and change the prompt to save(Yes/No)?
        }

        private void textBoxContent_TextChanged(object sender, EventArgs e)
        {
            if (gNewTextLoaded == true)
                gTextContentChanged = true;
        }
        private bool SaveFile(string lFileName)
        {
            MessageBox.Show("procedure to Save file, called.");
            return true;
        }

        private void lblAppStatus_Click(object sender, EventArgs e)
        {

        }

        private void lblLink_Click(object sender, EventArgs e)
        {

        }

        private void toolStripMenuItemReadingView_Click(object sender, EventArgs e)
        {
            if (toolStripMenuItemReadingView.Text == "Reading View")
            {
                this.splitContainerMain.Panel1Collapsed = true;
                toolStripMenuItemReadingView.Text = "Normal View";
                //toolStripMenuItemReadingView.Image = Browsepad.Properties.Resources.speaker;
            }
            else
            {
                this.splitContainerMain.Panel1Collapsed = false;
                toolStripMenuItemReadingView.Text = "Reading View";
                //toolStripMenuItemReadingView.Image = Browsepad.Properties.Resources.speaker_blue;
            }



        }

    }
}
